#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <iostream>
int main()
{
	char hostname[256];
	char ip[256];
	struct hostent* host;

	gethostname(hostname, 256);
	printf("hostname = %s\n",hostname);
	host = gethostbyname(hostname);
	if(host != nullptr)
	{
		printf("ip = %s\n",inet_ntoa(*(struct in_addr*)host->h_addr_list[0]));
	}
	else 
	{
		printf("无法获取本地IP地址");
	}

//方法二
   addrinfo *addr_info = NULL;
   char hostName[100];
	 memset(&ip,0,256);

   gethostname(hostName, sizeof(hostName));
	 std::cout << hostName << std::endl;
 
   int err = getaddrinfo(hostName,NULL,NULL,&addr_info);
   in_addr ipaddr =(((sockaddr_in*)(addr_info->ai_addr))->sin_addr);
   strcpy(ip,inet_ntoa(ipaddr));
	 std::cout << ip << std::endl;

	return 0;
}
